package com.gateway.security.common.authentication.client;

import org.springframework.security.core.GrantedAuthority;

import java.io.Serial;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: api-gateway
 * @description:
 * @author: YuKai Fan
 * @create: 2025/2/11 21:22
 **/
public class DefaultClientPrincipal implements ClientPrincipal {
    private final Map<String, Object> claims;

    private final static String AUTHORITIES = "authorities";
    private final static String PRINCIPAL = "principal";
    private final static String NAME = "name";

    public DefaultClientPrincipal(Map<String, Object> claims) {
        this.claims = claims;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Object object = claims.get(AUTHORITIES);
        if (object == null) {
            return Collections.emptyList();
        }
        if (object instanceof List<?> list) {
            return list.stream()
                    .map(o -> new GrantedAuthority() {
                        @Serial
                        private static final long serialVersionUID = 5657988443406019754L;
                        @Override
                        public String getAuthority() {
                            return String.valueOf(o);
                        }
                    }).collect(Collectors.toSet());
        }
        return Collections.emptyList();
    }

    @Override
    public Object getPrincipal() {
        return claims.get(PRINCIPAL);
    }

    @Override
    public String getName() {
        Object object = claims.get(NAME);
        return object != null ? String.valueOf(object) : "Default";
    }
}
